from ros2webserver.baseserver.capability import Capability
import json
from ros2webserver_msgs.srv import ProcessOp
import os

class CameraToStream(Capability):

    def __init__(self, protocol):
        Capability.__init__(self, protocol)
        protocol.register_operation("openCamera", self.open_camera)
        protocol.register_operation("closeCamera", self.close_camera)

        self.result = {
                "op":"open_camera",
                "code":1,
                "msg":"",  
                "data":None
        }
    
    def req_process_op(self,name,op,command="",callback=None):
        self.process_op_client = self.protocol.node_handle.create_client(ProcessOp, 'process_op')
        if not self.process_op_client.wait_for_service(timeout_sec=1.0):
            self.protocol.node_handle.get_logger().info('ProcessOp service not available, waiting...')
            self.result['code'] = 1
            self.result['msg'] = 'fail'
            self.protocol.send(self.result)
        request = ProcessOp.Request()
        request.name = name
        request.op = op
        request.command = command
        future = self.process_op_client.call_async(request)
        if callback:
            future.add_done_callback(callback)

    def run_camera2stream(self,future):
        def startup_finish(future):
            self.result['code'] = 0
            self.result['msg'] = 'ok'
            self.protocol.send(self.result)
        response = future.result()
        self.req_process_op('camera2stream',ProcessOp.Request.OP_RUN,callback=startup_finish)

    def add_camera2stream(self, topic="/camera_sensor/image_raw"):
        command = f"ros2 run sensor_forward camera2http {topic}"
        self.req_process_op('camera2stream',ProcessOp.Request.OP_ADD,command=command,callback=self.run_camera2stream)

    def check_starup_status(self,map_name):
        pass
    def open_camera(self, message):
        self.protocol.node_handle.get_logger().info(f"{message}")
        self.result['op'] = message['op']
        data = message['data']
        self.add_camera2stream(topic=data['topic'])

    def close_camera(self,message):
        self.result['op'] = message['op']
        def stop_result(future):
            res = future.result()
            print(res)
            result = self.result
            result['op'] = message['op']
            result['code'] = 0
            result['msg'] = 'ok'
            self.protocol.send(result)
        self.req_process_op('camera2stream',ProcessOp.Request.OP_STOP,callback=stop_result)

    def finish(self):
        pass
